package com.fjwt.gz.service.activity;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.interfaces.IOfficialService;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.core.utils.WxUtil;
import com.fjwt.gz.db.base.BaseAgentApp;
import com.fjwt.gz.db.config.dynamic.WxMpProperties;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.dto.FansUserDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.db.vo.AgentAppVO;
import com.fjwt.gz.service.impl.*;
import com.fjwt.gz.service.mapper.ActivityMapper;
import com.fjwt.gz.util.Utils;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户参与活动   条件验证
 *
 * @Author Will
 * @date 2024-4-1
 */
@Slf4j
@Service
public abstract class BaseActivityService<T> extends ServiceImpl<ActivityMapper, ActivityEntity> {

    @Value("${isFormal.code}")
    private boolean isFormalCode;

    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityShareService activityShareService;
    @Autowired
    private AwardCouponService awardCouponService;
    @Autowired
    private AwardGoodsService awardGoodsService;
    @Autowired
    private AwardScoreService awardScoreService;
    @Autowired
    private ActivityAppService activityAppService;
    @Autowired
    private AgentAppService agentAppService;
    @Autowired
    private FansActivityService fansActivityService;
    @Autowired
    private FansUserService fansUserService;
    @Autowired
    private HelpRecordService helpRecordService;
    @Autowired
    private FansService fansService;
    @Autowired
    private ActivityBlacklistService activityBlacklistService;
    @Autowired
    private FansSourceService fansSourceService;
    @Autowired
    private OfficialMaterialService officialMaterialService;

    /**
     * 活动数据
     */
    protected ActivityEntity activityEntity;

    /**
     * 用户数据
     */
    protected FansEntity fansEntity;

    /**
     * 活动开始日期
     */
    protected Date startDate;

    /**
     * 活动结束日期
     */
    protected Date endDate;

    /**
     * 缓存数据过期时间段
     */
    protected Long redisOutTime;


    /**
     * 用户商户号
     */
    protected String mchNo;

    /**
     * 真实姓名
     */
    protected String realName;

    /**
     * 配置状态：草稿
     */
    protected final int STATE_DRAFT = 0;

    /**
     * 配置状态：未通过
     */
    protected final int STATE_FAIL = 3;

    /**
     * 配置状态：通过
     */
    protected final int STATE_SUCCESS = 2;

    /**
     * 其他地方需要额外执行的操作
     */
    @Transactional
    public void shareRun(JSONObject jsonObject) {

    }

    /**
     * 实名认证后的操作逻辑
     */
    public void realNameAfter(FansAwardEntity fansAwardEntity) {

    }

    /**
     * 实名认证后的操作逻辑
     */
    public void realNameAfter(JSONObject jsonObject) {
    }

    /**
     * 其他地方需要额外执行的操作
     */
    @Transactional
    public void run(JSONObject jsonObject) throws Exception {};

    @Transactional
    public void add(BaseActivityDTO<T> activityDTO) {
        log.info("新建活动请求参数: {}", JSONUtil.toJsonStr(activityDTO));
        Date date = new Date();
//      新增活动主表
        ActivityEntity activityEntity = new ActivityEntity();
        BeanUtils.copyProperties(activityDTO, activityEntity);//copy properties
        activityEntity.setCreatedAt(date);
        this.save(activityEntity);
        Long activityId = activityEntity.getActivityId();
        log.info("活动主表新增成功，返回主键ID " + activityId);

        if (activityDTO.getWxOfficalAppId() != null) {

            ActivityAppEntity activityAppEntity = new ActivityAppEntity();
            activityAppEntity.setActivityId(activityId);
            activityAppEntity.setAppId(activityDTO.getWxOfficalAppId());
            activityAppEntity.setType(0);
            //新增活动绑定小程序公众号
            activityAppService.save(activityAppEntity);
        }
        if (activityDTO.getWxMiniProgramAppId() != null) {

            ActivityAppEntity activityAppEntity = new ActivityAppEntity();
            activityAppEntity.setActivityId(activityId);
            activityAppEntity.setAppId(activityDTO.getWxMiniProgramAppId());
            activityAppEntity.setType(1);
            //新增活动绑定小程序公众号
            activityAppService.save(activityAppEntity);
        }

        List<BaseActivityDTO.ActivityAward> activityAwardList = activityDTO.getActivityAwardList();
        if (activityAwardList != null && !activityAwardList.isEmpty()) {
            // 判断活动绑定卡券是否已上线
            activityAwardService.checkActivityAward(activityAwardList);
            List<ActivityAwardEntity> activityAwardEntityList = new ArrayList<>();
            for (BaseActivityDTO.ActivityAward activityAward : activityAwardList) {
                ActivityAwardEntity activityAwardEntity = new ActivityAwardEntity();
                BeanUtils.copyProperties(activityAward, activityAwardEntity);
                activityAwardEntity.setActivityId(activityId);
                activityAwardEntity.setCreatedAt(date);
                activityAwardEntityList.add(activityAwardEntity);
            }
            activityAwardService.saveBatch(activityAwardEntityList);
            log.info("活动奖品表新增成功");
        }

        BaseActivityDTO.ActivitySetting activitySetting = activityDTO.getActivitySetting();
        if (activitySetting != null) {
            ActivitySettingEntity activitySettingEntity = new ActivitySettingEntity();
            BeanUtils.copyProperties(activitySetting, activitySettingEntity);
            activitySettingEntity.setActivityId(activityId);
            activitySettingEntity.setCreatedAt(date);
            if (null != activitySetting.getOverType() && 2 == activitySetting.getOverType()) {
                activitySetting.setOverTime(Utils.firstMonthLastDay());
            }
            activitySettingService.save(activitySettingEntity);
            log.info("活动配置表新增成功");
            if (activitySetting.getHasBlacklist() == 1) {
                //添加活动黑名单限制
                List<Long> ruleIdList = activitySetting.getBlacklistRuleIdList();
                addBlacklistRule(ruleIdList, activityId);
            }
        }

        ActivityShareEntity activityShareEntity = activityDTO.getActivityShare();
        if (null != activityShareEntity) {
            activityShareEntity.setActivityId(activityId);
            activityShareEntity.setCreatedAt(new Date());
            activityShareService.save(activityShareEntity);
            log.info("活动分享配置表新增成功");
        }

        if (activityDTO.getState() != null && activityDTO.getState() == 1) {
            activityService.addAuditRecords(activityId);
        }
    }

    /**
     * 添加活动黑名单规则
     */
    private void addBlacklistRule(List<Long> ruleIdList, Long activityId) {
        log.info("添加活动黑名单规则id列表：{}", JSON.toJSONString(ruleIdList));
        if (CollUtil.isEmpty(ruleIdList) || activityId == null) {
            return;
        }
        List<ActivityBlacklistEntity> activityBlacklistEntityList = new ArrayList<>();
        for (Long ruleId : ruleIdList) {
            ActivityBlacklistEntity activityBlacklistEntity = new ActivityBlacklistEntity();
            activityBlacklistEntity.setActivityId(activityId);
            activityBlacklistEntity.setBlacklistRuleId(ruleId);
            activityBlacklistEntityList.add(activityBlacklistEntity);
        }
        activityBlacklistService.saveBatch(activityBlacklistEntityList);
        log.info("黑名单限制表新增成功");
    }

    /**
     * 查询活动详情
     */
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看活动详情，请求参数activityId:{} ", activityId);
        BaseActivityDTO baseActivityDetailsVO = new BaseActivityDTO();
        ActivityEntity activityEntity = getById(activityId);
        if (activityEntity == null) {
            throw new BizException("该活动不存在");
        } else {
            LambdaQueryWrapper<OfficialMaterialEntity> officialMaterialWrapper = OfficialMaterialEntity.gw().eq(OfficialMaterialEntity::getMediaId, activityEntity.getThumbMediaId());
            List<OfficialMaterialEntity> officialMaterialList = officialMaterialService.list(officialMaterialWrapper);
            if (ObjectUtils.isNotEmpty(officialMaterialList)){
                baseActivityDetailsVO.setImgUrl(officialMaterialList.get(0).getImgUrl());
            }
            BeanUtils.copyProperties(activityEntity, baseActivityDetailsVO);
        }
        LambdaQueryWrapper<ActivitySettingEntity> activitySettingWrapper = new LambdaQueryWrapper<>();
        activitySettingWrapper.eq(ActivitySettingEntity::getActivityId, activityId);
        ActivitySettingEntity activitySettingEntity = activitySettingService.getOne(activitySettingWrapper);
        if (activitySettingEntity != null) {
            baseActivityDetailsVO.setActivitySetting(new BaseActivityDTO.ActivitySetting());
            BeanUtils.copyProperties(activitySettingEntity, baseActivityDetailsVO.getActivitySetting());
            if (activitySettingEntity.getHasBlacklist() == 1) {
                //查询活动绑定的黑名单列表
                List<ActivityBlacklistEntity> blacklistEntityList = activityBlacklistService.list(ActivityBlacklistEntity.gw()
                        .eq(ActivityBlacklistEntity::getActivityId, activityId));
                List<Long> ruleIdList = blacklistEntityList.stream().map(ActivityBlacklistEntity::getBlacklistRuleId).toList();
                baseActivityDetailsVO.getActivitySetting().setBlacklistRuleIdList(ruleIdList);
            }
        }
        LambdaQueryWrapper<ActivityShareEntity> gw = ActivityShareEntity.gw();
        gw.eq(ActivityShareEntity::getActivityId, activityId);
        ActivityShareEntity activityShareEntity = activityShareService.getOne(gw);
        baseActivityDetailsVO.setActivityShare(activityShareEntity);

        LambdaQueryWrapper<ActivityAwardEntity> activityAwardWrapper = new LambdaQueryWrapper<>();
        activityAwardWrapper.eq(ActivityAwardEntity::getActivityId, activityId);
        List<ActivityAwardEntity> activityAwardEntityList = activityAwardService.list(activityAwardWrapper);
        if (activityAwardEntityList != null && !activityAwardEntityList.isEmpty()) {
            List<BaseActivityDTO.ActivityAward> activityAwardList = new ArrayList<>();
            for (ActivityAwardEntity entity : activityAwardEntityList) {
                BaseActivityDTO.ActivityAward activityAward = new BaseActivityDTO.ActivityAward();
                BeanUtils.copyProperties(entity, activityAward);
                Long awardId = entity.getAwardId();
                switch (entity.getAwardType()) {
                    case Constants.AWARD.COUPON:
                        AwardCouponEntity awardCouponEntity = awardCouponService.getById(awardId);
                        activityAward.setAwardPrice(awardCouponEntity.getCouponPrice());
                        activityAward.setAwardAmount(awardCouponEntity.getCouponAmount());
                        activityAward.setAwardNum(awardCouponEntity.getCouponNum());
                        activityAward.setAwardGet(awardCouponEntity.getCouponGet());
                        activityAward.setPayConfig(awardCouponEntity.getPayConfig());
                        break;
                    case Constants.AWARD.GOODS:
                        AwardGoodsEntity goodsAwardEntity = awardGoodsService.getById(awardId);
                        activityAward.setAwardPrice(goodsAwardEntity.getGoodsPrice());
                        activityAward.setAwardAmount(goodsAwardEntity.getGoodsAmount());
                        activityAward.setAwardNum(goodsAwardEntity.getGoodsNum());
                        break;
                    case Constants.AWARD.SCORE:
                        AwardScoreEntity scoreAwardEntity = awardScoreService.getById(awardId);
                        activityAward.setAwardPrice(scoreAwardEntity.getScoreValue());
                        activityAward.setAwardAmount(scoreAwardEntity.getScoreAmount());
                        activityAward.setAwardNum(scoreAwardEntity.getScoreNum());
                        break;
                }

                activityAwardList.add(activityAward);
            }
            baseActivityDetailsVO.setActivityAwardList(activityAwardList);
        }

        LambdaQueryWrapper<ActivityAppEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ActivityAppEntity::getActivityId, activityId);
        List<ActivityAppEntity> activityAppEntity = activityAppService.list(queryWrapper);
        if (activityAppEntity != null) {
            for (ActivityAppEntity entity : activityAppEntity) {
                if (entity.getType() == 0) {
                    baseActivityDetailsVO.setWxOfficalAppId(entity.getAppId());
                }
                if (entity.getType() == 1) {
                    baseActivityDetailsVO.setWxMiniProgramAppId(entity.getAppId());
                }
            }
        }

        return baseActivityDetailsVO;
    }

    /**
     * 修改活动
     */
    @Transactional
    public void update(BaseActivityDTO<T> activityDTO) {
        log.info("修改活动请求参数: {} ", JSONUtil.toJsonStr(activityDTO));
        Long activityId = activityDTO.getActivityId();
        Date date = new Date();
        ActivityEntity activityEntity = getById(activityId);
        if (activityEntity == null) {
            throw new BizException("该记录不存在");
        }
        Integer state = activityEntity.getState();

        if (activityDTO.getWxOfficalAppId() != null) {
            LambdaQueryWrapper<AgentAppEntity> gw = AgentAppEntity.gw();
            gw.eq(AgentAppEntity::getAppId, activityDTO.getWxOfficalAppId());
            gw.eq(AgentAppEntity::getType, 0);
            AgentAppEntity agentAppEntity = agentAppService.getOne(gw);

            LambdaQueryWrapper<ActivityAppEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ActivityAppEntity::getActivityId, activityId);
            queryWrapper.eq(ActivityAppEntity::getType, agentAppEntity.getType());
            ActivityAppEntity activityAppEntity = activityAppService.getOne(queryWrapper);
            if (activityAppEntity != null) {
                activityAppEntity.setAppId(String.valueOf(activityDTO.getWxOfficalAppId()));
                activityAppEntity.setType(0);
                //修改活动绑定小程序公众号
                activityAppService.updateById(activityAppEntity);
            } else {
                activityAppEntity = new ActivityAppEntity();
                activityAppEntity.setActivityId(activityId);
                activityAppEntity.setAppId(String.valueOf(activityDTO.getWxOfficalAppId()));
                activityAppEntity.setType(0);
                //新增活动绑定小程序公众号
                activityAppService.save(activityAppEntity);
            }

        }
        if (activityDTO.getWxMiniProgramAppId() != null) {
            LambdaQueryWrapper<AgentAppEntity> gw = AgentAppEntity.gw();
            gw.eq(AgentAppEntity::getAppId, activityDTO.getWxMiniProgramAppId());
            gw.eq(AgentAppEntity::getType, 1);
            AgentAppEntity agentAppEntity = agentAppService.getOne(gw);
            if (agentAppEntity == null) {
                throw new BizException("小程序信息不存在");
            }
            LambdaQueryWrapper<ActivityAppEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ActivityAppEntity::getActivityId, activityId);
            queryWrapper.eq(ActivityAppEntity::getType, agentAppEntity.getType());
            ActivityAppEntity activityAppEntity = activityAppService.getOne(queryWrapper);
            if (activityAppEntity != null) {
                activityAppEntity.setAppId(String.valueOf(activityDTO.getWxMiniProgramAppId()));
                activityAppEntity.setType(1);
                //修改活动绑定小程序公众号
                activityAppService.updateById(activityAppEntity);
            } else {
                activityAppEntity = new ActivityAppEntity();
                activityAppEntity.setActivityId(activityId);
                activityAppEntity.setAppId(String.valueOf(activityDTO.getWxMiniProgramAppId()));
                activityAppEntity.setType(1);
                //新增活动绑定小程序公众号
                activityAppService.save(activityAppEntity);
            }

        }

        if (state == STATE_FAIL || state == STATE_DRAFT) {
            BeanUtils.copyProperties(activityDTO, activityEntity);//copy properties
            activityEntity.setUpdatedAt(date);
            activityEntity.setCreatedAt(null);
            System.out.println(activityEntity.getStartTime());
            this.updateById(activityEntity);
            log.info("活动主表修改成功");


            ActivityShareEntity activityShareEntity = activityDTO.getActivityShare();
            if (null != activityShareEntity) {
                activityShareEntity.setActivityId(activityId);
                activityShareService.saveOrUpdate(activityShareEntity);
                log.info("活动分享配置表表修改成功");
            }


            LambdaQueryWrapper<ActivityAwardEntity> activityAwardWrapper = new LambdaQueryWrapper<>();
            activityAwardWrapper.eq(ActivityAwardEntity::getActivityId, activityId);
            activityAwardService.remove(activityAwardWrapper);
            log.info("活动旧奖品删除成功");
            List<BaseActivityDTO.ActivityAward> activityAwardList = activityDTO.getActivityAwardList();
            if (activityAwardList != null && !activityAwardList.isEmpty()) {
                // 判断活动绑定卡券是否已上线
                activityAwardService.checkActivityAward(activityAwardList);
                List<ActivityAwardEntity> activityAwardEntityList = new ArrayList<>();
                for (BaseActivityDTO.ActivityAward activityAward : activityAwardList) {
                    ActivityAwardEntity activityAwardEntity = new ActivityAwardEntity();
                    BeanUtils.copyProperties(activityAward, activityAwardEntity);
                    activityAwardEntity.setActivityId(activityId);
                    activityAwardEntity.setCreatedAt(date);
                    activityAwardEntityList.add(activityAwardEntity);
                }
                activityAwardService.saveBatch(activityAwardEntityList);
                log.info("活动新奖品新增成功");
            }

            BaseActivityDTO.ActivitySetting activitySetting = activityDTO.getActivitySetting();
            if (activitySetting != null) {
                ActivitySettingEntity activitySettingEntity = new ActivitySettingEntity();
                BeanUtils.copyProperties(activitySetting, activitySettingEntity);
                if (null != activitySetting.getOverType() && 2 == activitySetting.getOverType()) {
                    activitySetting.setOverTime(Utils.firstMonthLastDay());
                }
                activitySettingService.updateById(activitySettingEntity);
                log.info("活动配置表更新成功");
                //是否开启黑名单
                Integer hasBlacklist = activitySetting.getHasBlacklist();
                if (hasBlacklist != null) {
                    //删除活动对应黑名单规则信息
                    activityBlacklistService.remove(ActivityBlacklistEntity.gw()
                            .eq(ActivityBlacklistEntity::getActivityId, activityId));
                    if (hasBlacklist == 1) {
                        //添加修改后的黑名单规则
                        List<Long> blacklistRuleIdList = activitySetting.getBlacklistRuleIdList();
                        addBlacklistRule(blacklistRuleIdList, activityId);
                        //清除redis缓存
                        String activityBlacklistRuleKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, activityId,
                                Constants.REDIS_ACTIVITY.ACTIVITY_BLACKLIST);
                        RedisUtil.del(activityBlacklistRuleKey);
                    }
                }
            }
        } else {
            throw new BizException("该状态不允许修改！");
        }

        if (activityDTO.getState() != null && activityDTO.getState() == 1) {
            activityService.addAuditRecords(activityId);
        }
    }

    /**
     * 用户活动奖品列表
     *
     * @param fansActivityDTO
     * @return
     */
    public JSONObject getActivityAwards(FansActivityDTO fansActivityDTO) {
        return null;
    }

    /**
     * 用户活动奖品列表
     *
     * @param fansActivityDTO
     * @return
     */
    public List<FansAwardEntity> getActivityAwardItems(FansActivityDTO fansActivityDTO) {
        return null;
    }


    /**
     * 参与活动
     */
    @Transactional
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        Long fansId = fansActivityDTO.getFansId();
        Long activityId = fansActivityDTO.getActivityId();
        Long shareFansId = fansActivityDTO.getShareFansId();
        log.info(String.format("用户开始参与活动======》用户fansId：%s，活动Id：%s", fansId, activityId));
//      检测活动基本信息
        String activityKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, activityId, Constants.REDIS_ACTIVITY.BASE_INFO);
        activityEntity = RedisUtil.getObject(activityKey, ActivityEntity.class);
        boolean isExistActivity = false;
        if (activityEntity == null) {
            activityEntity = getById(activityId);
            if (activityEntity == null) {
                throw new BizException("当前活动不存在");
            }
        } else {
            isExistActivity = true;
            log.info(String.format("活动主表在Redis中存在，ID: %s", activityId));
        }
        if (activityEntity.getState() != 4) {
            throw new BizException("当前活动未上线");
        }
        Long currentDate = System.currentTimeMillis();
        startDate = activityEntity.getStartTime();
        if (startDate.getTime() > currentDate) {
            throw new BizException("当前活动还未开始");
        }
        endDate = activityEntity.getEndTime();
        redisOutTime = endDate.getTime() - DateUtil.date().getTime();
        if (endDate != null && endDate.getTime() < currentDate) {
            throw new BizException("当前活动已结束");
        }
        if (!isExistActivity) {
            RedisUtil.set(activityKey, activityEntity, redisOutTime, TimeUnit.MILLISECONDS);
            log.info("活动主表存入Redis中且设置过期时间， ID：{}， endDate:{}", activityId, endDate);
        }

        //        检测用户信息
        fansEntity = fansService.getById(fansId);
        if (fansEntity == null) {
            throw new BizException("当前用户不存在");
        }
        log.info("用户基本信息：{}", JSONUtil.toJsonStr(fansEntity));
        // 查询活动配置信息
        ActivitySettingEntity activitySettingEntity = activitySettingService.getActivitySettingEntity(activityId, redisOutTime);
        // 查询用户公众号信息
        if (activitySettingEntity != null && activitySettingEntity.getIsFollowOfficial() != null && activitySettingEntity.getIsFollowOfficial() == 1) {
            //查询活动公众号信息
            FansUserDTO fansUerInfo = activityAppService.getFansUerByActivityId(activityId, fansId);
            log.info("地域公众号下的用户信息：{}", JSON.toJSONString(fansUerInfo));
            if (fansUerInfo == null || StringUtils.isNullOrEmpty(fansUerInfo.getOpenId()) || StringUtils.isNullOrEmpty(fansEntity.getPhone())) {
                log.info("请先完善个人信息");
                if ("ACTE006".equals(activityEntity.getActivityTemplateNo())) {
                    if (fansUerInfo == null){
                        ActivityAppEntity activityAppEntity = activityAppService.lambdaQuery().eq(ActivityAppEntity::getActivityId, activityId).eq(ActivityAppEntity::getType, 1).one();
//                        AgentAppVO agentAppVO = agentAppService.selectOfficial(activityAppEntity.getAppId());
                        ActivityEntity activityEntity = activityService.getById(activityId);
                        // 查询app秘钥
                        BaseAgentApp agentApp = agentAppService.getAgentApp(activityAppEntity.getAppId());
                        // 生成小程序码
                        String qrCode = WxUtil.getUnlimitedQRCode(activityAppEntity.getActivityId(), activityAppEntity.getAppId(), agentApp.getAppSecret(), activityEntity.getEndTime().getTime() - System.currentTimeMillis(), isFormalCode);
                        throw new BizException(ApiCodeEnum.LITE_USER_SUBJECT_OFFICIAL_ERROR, qrCode);
                    }
                    throw new BizException("请领取用户完善个人信息");
                } else {
                    throw new BizException("请先完善个人信息");
                }
            }
            if (fansUerInfo.getIsFollow() == null || fansUerInfo.getIsFollow() == 1) {
                IOfficialService service = SpringBeansUtil.getBean("officialWxChatService", IOfficialService.class);
                if (ObjectUtils.isEmpty(service)){
                    throw new BizException("网络故障，请稍后重试！");
                }
                BaseAgentApp agentApp = agentAppService.getAgentApp(fansUerInfo.getAppId());
                if (ObjectUtils.isEmpty(agentApp)){
                    throw new BizException("机构公众号不存在！");
                }
                log.info("机构公众号 agentApp：{}", agentApp);
                WxMpService wxService = getWxService(fansUerInfo.getAppId(), agentApp.getAppSecret());
                boolean isFollow = service.getUserInfo(fansUerInfo.getOpenId(), fansUerInfo.getAppId(), wxService);
                if (!isFollow) {
                    log.info("用户未关注地域公众号，用户fanId:{}", fansId);
                    if (!StringUtils.isNullOrEmpty(agentApp.getImgUrl())) {
                        log.info("地域公众号图片URL:{}", agentApp.getImgUrl());
                        String activityTemplateNo = activityEntity.getActivityTemplateNo();
                        if ("ACTE006".equals(activityTemplateNo)) {
                            throw new BizException(String.format("领取用户未关注%s公众号", agentApp.getName()));
                        } else {
                            throw new BizException(ApiCodeEnum.LITE_USER_NO_OFFICIAL_ERROR, agentApp.getImgUrl());
                        }
                    } else {
                        log.info("地域公众号图片URL不存在");
                        throw new BizException("地域公众号图片URL不存在");
                    }
                } else {
                    FansUserEntity fansUserEntity = new FansUserEntity();
                    fansUserEntity.setIsFollow(0);
                    fansUserEntity.setFansUserId(fansUerInfo.getFansUserId());
                    fansUserService.updateById(fansUserEntity);
                    log.info("更新用户关注地域公众号状态为已关注，用户fansUserID:{}", fansUserEntity.getFansUserId());
                }
            }
        }

        //判断没有分享人UserId直接返回
        if (shareFansId == null) {
            log.info("没有分享人userId");
            return null;
        }


        //判断活动是否要添加分享记录
        LambdaQueryWrapper<ActivityShareEntity> gw = ActivityShareEntity.gw();
        gw.eq(ActivityShareEntity::getActivityId, activityId);
        ActivityShareEntity activityShareEntity = activityShareService.getOne(gw);
        if (ObjectUtils.isEmpty(activityShareEntity)) {
            log.info("活动没有配置分享规则");
            return null;
        }
        //自己分享给自己
        if (shareFansId == fansId) {
            log.info("自己不能分享自己");
            return null;
        }

        //判断最大分享次数
        LambdaQueryWrapper<HelpRecordEntity> shareRecordGw = HelpRecordEntity.gw();
        shareRecordGw.eq(HelpRecordEntity::getActivityId, activityId);
        shareRecordGw.eq(HelpRecordEntity::getFansId, shareFansId);
        shareRecordGw.eq(HelpRecordEntity::getIsSuccess, 1);
        List<HelpRecordEntity> shareRecordList = helpRecordService.list(shareRecordGw);
        if (shareRecordList.size() >= activityShareEntity.getShareMaxNum()) {
            log.info("最大分享次数已经达到限制");
            return null;
        }

        FansSourceEntity fansSourceEntity = fansSourceService.lambdaQuery().eq(FansSourceEntity::getFansId, fansId).eq(FansSourceEntity::getActivityId, activityId).one();

        //分享成功标准
        addHelpRecord(activityShareEntity, fansId, activityId, shareFansId, fansSourceEntity, activityEntity);
        return null;
    }

    public void handleActivityAwardBO(FansActivityDTO fansActivityDTO) {
    }

    /**
     * 获取微信公众号service
     **/
    public WxMpService getWxService(String appid, String appsecret) {

        List<WxMpProperties.MpConfig> configs = new ArrayList<>();

        WxMpProperties.MpConfig mpConfig = new WxMpProperties.MpConfig();
        mpConfig.setAppId(appid);
        mpConfig.setSecret(appsecret);
        mpConfig.setToken(null);
        mpConfig.setAesKey(null);
        configs.add(mpConfig);

        log.info("公众号配置参数信息：{}", JSON.toJSONString(configs));
        WxMpService service = new WxMpServiceImpl();
        service.setMultiConfigStorages(configs
                .stream().map(a -> {
                    WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
                    configStorage.setAppId(a.getAppId());
                    configStorage.setSecret(a.getSecret());
                    configStorage.setToken(a.getToken());
                    configStorage.setAesKey(a.getAesKey());
                    configStorage.setUseStableAccessToken(true);
                    log.info("公众号发送消息时，相关配置信息（包括获取稳定版的token）：{}", JSON.toJSONString(configStorage));
                    return configStorage;
                }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));
        return service;
    }

    private JSONObject addHelpRecord(ActivityShareEntity activityShareEntity, Long fansId, Long activityId, Long shareFansId, FansSourceEntity fansSourceEntity, ActivityEntity activityEntity) {
        //分享成功标准
        Integer shareSuccessStandard = activityShareEntity.getShareSuccessStandard();
        if (0 == shareSuccessStandard) {

        } else if (1 == shareSuccessStandard) {
            //fansSource,用户来源表
            if (fansSourceEntity.getInviterId() == shareFansId) {
                log.info("该用户不是新用户，用户fansUserId:{}", fansSourceEntity.getFansId());
                //没参与过此活动，添加分享记录中
                HelpRecordEntity shareRecordEntity = new HelpRecordEntity();
                shareRecordEntity.setActivityId(activityId);
                shareRecordEntity.setCreatedAt(new Date());
                shareRecordEntity.setFansId(shareFansId);
                shareRecordEntity.setToFansId(fansId);
                shareRecordEntity.setIsSuccess(0);
                shareRecordEntity.setUpdatedAt(new Date());
                helpRecordService.save(shareRecordEntity);
                return null;
            }
        } else if (2 == shareSuccessStandard) {

            //查询用户是否参与过此活动
            LambdaQueryWrapper<FansActivityEntity> fansActivityEntityGw = FansActivityEntity.gw();
            fansActivityEntityGw.eq(FansActivityEntity::getFansId, fansId);
            fansActivityEntityGw.eq(FansActivityEntity::getActivityId, activityId);
            List<FansActivityEntity> fansActivityEntities = fansActivityService.getBaseMapper().selectList(fansActivityEntityGw);
            if (fansActivityEntities != null && fansActivityEntities.size() > 0) {
                log.info("被分享人已经参与过此活动，用户fansId:{}", fansId);
                return null;
            }
            //没参与过此活动，添加分享记录中
            HelpRecordEntity shareRecordEntity = new HelpRecordEntity();
            shareRecordEntity.setActivityId(activityId);
            shareRecordEntity.setCreatedAt(new Date());
            shareRecordEntity.setFansId(shareFansId);
            shareRecordEntity.setToFansId(fansId);
            shareRecordEntity.setIsSuccess(1);
            shareRecordEntity.setUpdatedAt(new Date());
            helpRecordService.save(shareRecordEntity);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("activityId", activityId);
            jsonObject.put("shareFansId", shareFansId);
            shareRun(jsonObject);
        } else if (3 == shareSuccessStandard) {
        }
        return null;
    }

    /**
     * 删除活动
     */
    @Transactional
    public void delete(Long activityId) {
        log.info("删除活动请求参数activityId:{} ", activityId);
        ActivityEntity activityEntity = getById(activityId);
        if (activityEntity == null) {
            throw new BizException("该记录不存在！");
        }
        Integer state = activityEntity.getState();
        if (state != STATE_DRAFT) {
            throw new BizException("非草稿状态，不能被删除！");
        }
        boolean activityRemove = removeById(activityId);
        log.info("活动activityId:{},主表删除activityRemove:{}", activityId, activityRemove);
        LambdaQueryWrapper<ActivityAppEntity> activityLimitMchWrapper = new LambdaQueryWrapper<>();
        activityLimitMchWrapper.eq(ActivityAppEntity::getActivityId, activityId);
        boolean activityLimitMchRemove = activityAppService.remove(activityLimitMchWrapper);
        log.info("活动activityId:{},商户中间表删除activityLimitMchRemove:{}", activityId, activityLimitMchRemove);
        LambdaQueryWrapper<ActivitySettingEntity> activitySettingWrapper = new LambdaQueryWrapper<>();
        activitySettingWrapper.eq(ActivitySettingEntity::getActivityId, activityId);
        boolean activitySettingRemove = activitySettingService.remove(activitySettingWrapper);
        log.info("活动activityId:{},配置表删除activitySettingRemove:{}", activityId, activitySettingRemove);
        LambdaQueryWrapper<ActivityAwardEntity> activityAwardWrapper = new LambdaQueryWrapper<>();
        activityAwardWrapper.eq(ActivityAwardEntity::getActivityId, activityId);
        boolean activityAwardRemove = activityAwardService.remove(activityAwardWrapper);
        log.info("活动activityId:{},奖品表删除activityAwardRemove:{}", activityId, activityAwardRemove);
    }

    /**
     * 导出报表
     **/
    public void exportActivityAward(ActivityEntity activityEntity, HttpServletResponse response) {}

    /**
     * 客户经理激活卡券处理
     **/
    public void fansActiveCoupon(FansAwardEntity fansAwardEntity) {
    }
}
